package com.cc.controller;

import com.cc.model.EbProduct;
import com.cc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/list")
    public ModelAndView list(@RequestParam(value = "page",defaultValue = "1") int page,
                             @RequestParam(value = "pageSize",defaultValue = "3")int pageSize){
        //1.获取新闻表的第一页数据，每页三条
        List<EbProduct> productlist = productService.list(page,pageSize);
        //获取最大页数
        int maxPage = productService.getMaxPage(pageSize);
        //2.将数据（List）和视图（jsp）返回给中央控制器
        ModelAndView mv = new ModelAndView();
        //绑定数据
        mv.addObject("products",productlist);
        //绑定当前页
        mv.addObject("curPage",page);
        //b绑定最大页
        mv.addObject("maxPage",maxPage);
        //绑定视图
        mv.setViewName("manage/product");
        return mv;
    }
    @RequestMapping("to_save")
    public String toSave(){
        return "manage/product-add";
    }
    @RequestMapping("/save")
    public String save(EbProduct ebProduct, MultipartFile pictrueFile, HttpServletRequest request){
        System.out.println(pictrueFile);
        System.out.println("进入ProductController.save==="+ebProduct+"\tpic=="+pictrueFile);
        //1.将数据添加到数据库(调用service)
        //1.1. 参数校验
        //1.2 将商品的信息保存到数据
        //1.2.1 设置商品的图片的名字
        String originFileName = pictrueFile.getOriginalFilename();
        ebProduct.setEp_file_name(originFileName);

        int result = productService.save(ebProduct);
        //1.3 文件上传（图片从客户端的电脑上上传到服务器(tomcat  images/products) ）
        //1.3.1指定上传到服务器的哪个路劲
        String rootPath = request.getServletContext().getRealPath("/");
        System.out.println("root:"+rootPath);
        String filePath = rootPath+"WEB-INF/images/product/"+originFileName;
        //创建文件
        File file =new File("WEB-INF/images/product/");
        if(!file.exists()){
            file.mkdir();
        }
        //1.3.2 上传
        try {
            pictrueFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("上传文件成功！！");
        //2.将成功的视图发送给 spring mvc的中央控制器

        return "manage/manage-result";
    }
    @RequestMapping("/edit")
    public String edit(Model model,Integer ep_id){
        //根据编号查询信息
        EbProduct ebProduct = productService.selectByCondition(ep_id);
        //将查出来的信息传递给product-modify.jsp
        model.addAttribute("ebProduct",ebProduct);
        return "manage/product-modify";
    }
    @RequestMapping("/editSubmit")
    public String editSubmit(EbProduct ebProduct){
        //更新信息
        System.out.println(ebProduct);
        int result = productService.updateById(ebProduct);
        //跳转到更新结果页面
        if(result<=0 ){
            return "manage/error";
        }
        return "manage/manage-result";
    }
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        //参数校验
        //执行删除
        int result = productService.deleteByPk(id);
        if(result==0){

        }
        return "manage/manage-result1";
    }

    @RequestMapping("/detail")
    public String detail(Model model,int epId){
        EbProduct ebProduct = productService.selectByCondition(epId);
        model.addAttribute("ebProduct",ebProduct);
        return "product-view";
    }

    @RequestMapping("/addCar")
    public String addCar(HttpServletRequest request, Integer epId){
        //1.根据id查询商品信息
        EbProduct productDetail = productService.selectByCondition(epId);
        //2.将商品放入购物车(session)
        //2.1得到购物车
        HttpSession session = request.getSession();
        //2.2 得到存放商品的集合
        Set<EbProduct> productSet= (Set<EbProduct>) session.getAttribute("productSet");
        //2.2.1 如果购物车中没有set集合，那么重新创建一个新的set集合
        if(productSet==null){
            productSet= new HashSet<>(5);

        }
        //2.3 将商品放入集合
        for(EbProduct product:productSet){
            //2.3.1判断是否是重复的商品
            if(product.getEp_id().equals(productDetail.getEp_id())){
                //2.3.1.1 重复的商品将数量+1
                productDetail.setCount(product.getCount()+1);
                //2.3.1.2 移除set中原有的商品
                productSet.remove(product);
            }
        }
        productSet.add(productDetail);

        //2.5 将集合放入购物车
        session.setAttribute("productSet",productSet);
        return "shopping";
    }

    @RequestMapping("/addCar1")
    public String addCar1(HttpServletRequest request, Integer epId){
        //1.根据id查询商品信息
        EbProduct productDetail = productService.selectByCondition(epId);
        //2.将商品放入购物车(session)
        //2.1得到购物车
        HttpSession session = request.getSession();
        //2.2 得到存放商品的集合
        Set<EbProduct> productSet= (Set<EbProduct>) session.getAttribute("productSet");
        //2.2.1 如果购物车中没有set集合，那么重新创建一个新的set集合
        if(productSet==null){
            productSet= new HashSet<>(5);

        }
        //2.3 将商品放入集合
        for(EbProduct product:productSet){
            //2.3.1判断是否是重复的商品
            if(product.getEp_id().equals(productDetail.getEp_id())){
                //2.3.1.1 重复的商品将数量+1
                productDetail.setCount(product.getCount()+1);
                //2.3.1.2 移除set中原有的商品
                productSet.remove(product);
            }
        }
        productSet.add(productDetail);

        //2.5 将集合放入购物车
        session.setAttribute("productSet",productSet);
        return "shopping";
    }
    @RequestMapping("/shopping-result")
    public String shopping(){
        return "shopping-result";
    }

    @RequestMapping("shop")
    public String shop(){
        return "shopping";
    }

}
